package com.powerunion.datacollection.web.struts;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.log4j.Logger;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;

import com.powerunion.datacollection.model.ApproveWorkItem;
import com.powerunion.datacollection.service.ApproveTargetsDataManager;
import com.powerunion.datacollection.service.ApproveWorkItemManager;
import com.powerunion.datacollection.service.DataCollectViewManager;
import com.powerunion.datacollection.service.MaintblDataManager;
import com.powerunion.datacollection.transaction.Transaction;
import com.powerunion.datacollection.transaction.TransactionHelper;
import com.powerunion.util.log.LogHelper;

public class SubFormDataCollectViewAction extends DispatchAction {

	private static final Logger logger = LogHelper.getInstance().getLogger(
			SubFormDataCollectViewAction.class);
	private DataCollectViewManager dcvManager = null;

	public SubFormDataCollectViewAction() {
		super();
		this.dcvManager = new DataCollectViewManager();
	}

	public void finalize() throws Throwable {
		this.dcvManager = null;
		super.finalize();
	}

	public ActionForward dataCollectView(ActionMapping mapping,
			ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String fsetId = request.getParameter("fsetId");
		request.setAttribute("fsetId", fsetId);

		String reType = request.getParameter("reType");
		request.setAttribute("reType", reType);

		String procId = request.getParameter("procId");
		request.setAttribute("procId", procId);

		String actId = request.getParameter("actId");
		request.setAttribute("actId", actId);

		String approveId = request.getParameter("approveId");
		request.setAttribute("approveId", approveId);

		String awState = request.getParameter("awState");
		request.setAttribute("awState", awState);

		String collectDataType = request.getParameter("collectDataType") == null ? "1"
				: request.getParameter("collectDataType");
		request.setAttribute("collectDataType", collectDataType);

		String iupdata = request.getParameter("iupdata") == null ? "8"
				: request.getParameter("iupdata");
		request.setAttribute("iupdata", iupdata);

		return mapping.findForward("subFormData.view");
	}

	public ActionForward getMaintblData(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		String actId = request.getParameter("actId");
		String procId = request.getParameter("procId");
		int currentOrparent = Integer.parseInt(request
				.getParameter("collectDataType"));

		MaintblDataManager mdm = new MaintblDataManager();
		String result = mdm.getAllMaintblDatasByAct(procId, actId,
				currentOrparent);
		logger.debug("getMaintblData:" + result);
		response.setContentType("text/json;charset=utf-8");
		try {
			response.getWriter().print(result);
		} catch (Exception e) {
			logger.error("输出json失败", e);
			response.getWriter().write("{failure:true}");
		}
		return null;
	}

	public ActionForward getTargetCategorys(ActionMapping mapping,
			ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String formId = request.getParameter("formId");

		JSONArray jsonArr = JSONArray.fromObject(this.dcvManager
				.getTargetsCategoryByFormId(formId));
		String result = "{results:" + jsonArr + "}";
		logger.debug("getActAllSubWorkIdNames:" + result);
		response.setContentType("text/json;charset=utf-8");
		try {
			response.getWriter().print(result);
			response.flushBuffer();

		} catch (Exception e) {
			logger.error("输出json失败", e);
			return null;
		}
		return null;
	}

	public ActionForward getGroupHeads(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		String actId = request.getParameter("actId");
		String procId = request.getParameter("procId");
		int flag = Integer.parseInt(request.getParameter("flag"));

		String result = this.dcvManager.getGroupHeadByAct(procId, actId, flag);
		logger.debug("getGroupHeads:" + result);
		response.setContentType("text/json;charset=utf-8");
		try {
			response.getWriter().print(result);
		} catch (Exception e) {
			logger.error("输出json失败", e);
			return null;
		}
		return null;
	}

	public ActionForward getTargettblData(ActionMapping mapping,
			ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String actId = request.getParameter("actId");
		String procId = request.getParameter("procId");
		String cid = request.getParameter("cid");
		int flag = Integer.parseInt(request.getParameter("flag"));

		List dc = this.dcvManager.getTargetDataCollectByAct(procId, actId, cid,
				flag);

		List ldc = new ArrayList();
		for (int i = 0; i < dc.size(); i++) {
			List l = (List) dc.get(i); // 表头对应的所有指标数据
			JSONObject record = new JSONObject();
			for (int j = 0; j < l.size(); j++) {
				record.put("column" + j, l.get(j));
			}
			ldc.add(record);
		}

		JSONArray jsonArr = JSONArray.fromObject(ldc);
		String result = "{results:" + jsonArr + "}";
		logger.debug("getGroupHeads:" + result);
		response.setContentType("text/json;charset=utf-8");
		try {
			response.getWriter().print(result);
		} catch (Exception e) {
			logger.error("输出json失败", e);
			return null;
		}
		return null;
	}

	public ActionForward getTemplateTargetInitData(ActionMapping mapping,
			ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String documentId = request.getParameter("formId");
		String procId = request.getParameter("procId");
		String approveId = request.getParameter("approveId");
		String actId = request.getParameter("actId");
		int flag = Integer.parseInt(request.getParameter("flag"));

		ApproveTargetsDataManager atm = new ApproveTargetsDataManager();

		List array = null;
		if (flag == 2) {// 获取该审批步骤下所有的上报数据
			//获取整合后的数据
			array = atm.getTargetSubmiData(documentId, procId, actId);
			if (array.isEmpty()) {//如果整合后的数据为空，则去读取原始数据
				array = this.dcvManager.getTemplateData(documentId, procId,actId);
			}

		} else {
			ApproveWorkItemManager awi = new ApproveWorkItemManager();
			ApproveWorkItem awit = awi.getByKey(approveId);
			int preActType = awit.getPreActType();
			if(preActType == 1){//当前上报的步骤为审批步骤
				array = this.dcvManager.getTemplateData(documentId, procId,awit.getPreActId());
			}else{//当前上报的步骤为采集步骤
				array = this.dcvManager.getTemplateDataByActId(documentId, procId,
						actId, approveId);
			}
		}

		JSONArray ja = JSONArray.fromObject(array);
		String result = "{results:" + ja + "}";
		logger.debug("getTemplateTargetInitData:" + result);
		response.setContentType("text/json;charset=utf-8");
		try {
			response.getWriter().print(result);
		} catch (IOException e) {
			logger.error("输出json失败", e);
			return null;
		}
		return null;
	}
	
	
	public ActionForward save (ActionMapping mapping,ActionForm form,
			HttpServletRequest request,HttpServletResponse response)
	        throws Exception {
		String saveStr = request.getParameter("targetsData");
		String procId = request.getParameter("procId");
		String actId = request.getParameter("actId");
		String approveId = request.getParameter("approveId");
		int currentOrParrent = Integer.parseInt(request.getParameter("currentOrParrent"));
		String updateUser = request.getRemoteUser();
		
		ApproveWorkItemManager awi = new ApproveWorkItemManager();
		ApproveWorkItem awit = awi.getByKey(approveId);
		int preActType = awit.getPreActType();
//		List submissionWorkItems = new ArrayList();
//		SubmissionWorkItemManager swm = new SubmissionWorkItemManager();
//		submissionWorkItems = swm.getAllSubWorksByAct(procId, awit.getPreActId(), currentOrParrent, preActType);
//		System.out.println("size:"+submissionWorkItems.size());
		
		
		
		boolean flag = false;
		
		Transaction transaction = null;
		try {
			transaction = TransactionHelper.getTransaction();
			transaction.begin();
			logger.debug("指标报送信息:" + saveStr);
			flag = this.dcvManager.save(saveStr, awit.getPreActId(), procId, updateUser, currentOrParrent,preActType);
//			if (currentOrParrent == 2) {//保存该审批步骤下所有的上报数据				
//				flag = this.dcvManager.save(saveStr, awit.getPreActId(), procId, updateUser, currentOrParrent,preActType);
//
//			} else {
//				if(preActType == 1){//当前上报的步骤为审批步骤
//					flag = this.dcvManager.save(saveStr, awit.getPreActId(), procId, updateUser, currentOrParrent,preActType);
//				}else{//当前上报的步骤为采集步骤
//					flag = this.dcvManager.save(saveStr, actId, procId, updateUser, currentOrParrent,preActType);
//				}
//			}

			//flag = this.dcvManager.save(saveStr, actId, procId, updateUser, currentOrParrent,preActType);

			transaction.commit();
		} catch (Exception e) {
			logger.error("", e);
			try {
				transaction.rollback();
			} catch (Exception e1) {
				logger.error("", e1);
				throw e;
			} finally {
				transaction = null;
				response.getWriter().write("{failure:true}");
			}
		}
		
		if (flag) {
			response.getWriter().write("{success:true}");
		} else {
			response.getWriter().write("{failure:true}");
		}
		
		return null;
	}

}
